package com.ybg.share.schedule;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.ybg.share.core.dbapi.entity.ShareStockEvaluate;
import com.ybg.share.core.dbapi.service.ShareStockEvaluateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;

/**
 * 千股千评定时任务
 */
@Component
@Slf4j
public class StockEvaluateJob {
    @Autowired
    private ShareStockEvaluateService shareStockEvaluateService;
    //    @Scheduled(cron = "0 0/1 * * * ?")
//    public void test(){
//        System.out.println("测试通过");
//    }


    /**
     * 千股千评 数据拉取
     */
    @Scheduled(cron = "0 30 21 * * ?")
    public void stockEvaluate() {




        try {
            String url = "http://data.eastmoney.com/stockcomment/";
            String page = HttpUtil.get(url);
            int index = page.indexOf("token");
            int end = page.indexOf("&", index);
            String token = page.substring(index, end).replace("token=", "");
            //获取token 没有token 拿不到数据
            int currentPage = 1;
            String dataUrl = getDataUrl(token, currentPage);
            stockEvaluateRetryGet = 10;
            String httpResult = getEvaluate(dataUrl);
            log.info(dataUrl);
            JSONObject jsonObject = JSONObject.parseObject(httpResult);
            int totolPage = jsonObject.getInteger("pages");
            for (int i = 1; i <= totolPage; i++) {
                stockEvaluateRetryGet = 10;
                String dataUrl_ = getDataUrl(token, i);
                String httpResult_ = getEvaluate(dataUrl_);
                log.info("请求结束，页数" + i);
                JSONObject jsonObject_ = JSONObject.parseObject(httpResult_);
                JSONArray jsonArray = jsonObject_.getJSONArray("data");

                for (int j = 0; j < jsonArray.size(); j++) {
                    try {
                        ShareStockEvaluate evaluate = new ShareStockEvaluate();
                        evaluate.setStockCode(jsonArray.getJSONObject(j).getString("Code"));
                        evaluate.setStockName(jsonArray.getJSONObject(j).getString("Name"));
                        evaluate.setLastUpdateTime(LocalDateTime.now());
                        evaluate.setChangePercent(getBigDecimal(jsonArray.getJSONObject(j), "ChangePercent"));
                        evaluate.setFocus(getBigDecimal(jsonArray.getJSONObject(j), "Focus"));
                        evaluate.setJgcyd(getBigDecimal(jsonArray.getJSONObject(j), "JGCYD", 2));
                        evaluate.setJgcydType(jsonArray.getJSONObject(j).getString("JGCYDType"));
                        evaluate.setNowPrice(getBigDecimal(jsonArray.getJSONObject(j), "New"));
                        evaluate.setRankingUp(getInteger(jsonArray.getJSONObject(j), "RankingUp", 9999));
                        evaluate.setTotalScore(getBigDecimal(jsonArray.getJSONObject(j), "TotalScore"));
                        evaluate.setTurnoverRate(getBigDecimal(jsonArray.getJSONObject(j), "TurnoverRate"));
                        evaluate.setZlcb(getBigDecimal(jsonArray.getJSONObject(j), "ZLCB", 2));
                        evaluate.setZlcb20r(getBigDecimal(jsonArray.getJSONObject(j), "ZLCB20R", 2));
                        evaluate.setZlcb60r(getBigDecimal(jsonArray.getJSONObject(j), "ZLCB60R", 2));
                        evaluate.setZljlr(getBigDecimal(jsonArray.getJSONObject(j), "ZLJLR", 2));
                        evaluate.setRanking(getInteger(jsonArray.getJSONObject(j), "Ranking", 9999));
                        evaluate.setPeRation(getBigDecimal(jsonArray.getJSONObject(j), "PERation"));
                        shareStockEvaluateService.saveReplace(evaluate);
//                    ThreadUtil.execute(new AbstractJob(evaluate) {
//                        @Override
//                        public void execute() {
//                            ShareStockEvaluate evaluate = (ShareStockEvaluate) getParams();
//                            shareStockEvaluateService.saveReplace(evaluate);
//                        }
//                    });
                    } catch (Exception e) {
                        log.info("jsonArray=" + jsonArray.getJSONObject(j).toJSONString());
                        log.info("该数据没有值 跳过，{}", e);
                    }


                }
            }
        } catch (Exception e) {
            log.info("error{}", e);

        } finally {

        }


    }

    /**
     * 千古千评 重试次数
     */
    static int stockEvaluateRetryGet = 10;

    private String getEvaluate(String dataUrl) {
        try {
            return HttpUtil.get(dataUrl, 10000);
        } catch (Exception e) {
            if (stockEvaluateRetryGet == 0) {
                return null;
            }
            stockEvaluateRetryGet--;
            return getEvaluate(dataUrl);
        }

    }

    private Integer getInteger(JSONObject json, String key, int defaultValue) {
        try {
            return json.getInteger(key);
        } catch (Exception e) {

        }
        return defaultValue;

    }

    private BigDecimal getBigDecimal(JSONObject json, String key) {
        try {
            return json.getBigDecimal(key);
        } catch (Exception e) {

        }
        return BigDecimal.ZERO;

    }

    private BigDecimal getBigDecimal(JSONObject json, String key, int scale) {
        try {
            return json.getBigDecimal(key).setScale(scale, RoundingMode.UP);
        } catch (Exception e) {

        }
        return BigDecimal.ZERO;

    }

    private String getDataUrl(String token, int currentPage) {
        return "http://dcfm.eastmoney.com/em_mutisvcexpandinterface/api/js/get?type=QGQP_LB&token=" + token + "&cmd=&st=Code&sr=1&p=" + currentPage + "&ps=50&js={pages:(tp),data:(x)}&filter=&rt=52604477";

    }

}
